package cc.eguid.commandManager.handler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 默认任务消息输出处理
 *
 * @author eguid
 * @version 2017年10月13日
 * @since jdk1.7
 */
public class ProgessHandlerMethod implements OutHandlerMethod {

	/**
	 * 任务是否异常中断，如果
	 */
	public boolean isBroken = false;

	public double duration = 0L;

	@Override
	public void parse(String id, String msg) {
		//过滤消息
		if (msg.indexOf("fail") != -1) {
			System.err.println(id + "任务可能发生故障：" + msg);
			System.err.println("失败，设置中断状态");
			isBroken = true;
		} else if (msg.indexOf("miss") != -1) {
			System.err.println(id + "任务可能发生丢包：" + msg);
			System.err.println("失败，设置中断状态");
			isBroken = true;
		} else {
			isBroken = false;
			if (duration == 0) {
				getDuration(msg);
			}
			if (duration != 0) {
				double curTime = currentTime(msg);
				System.err.println(id + "-进度：" + (curTime / duration) * 100 + "%");
			}
		}

	}

	private void getDuration(String msg) {
		Pattern pattern = Pattern.compile("Duration:[^,]*");
		Matcher matcher = pattern.matcher(msg);
		long second = 1;
		long minute = second * 60;
		long hour = minute * 60;
		while (matcher.find()) {
			String timeStr = matcher.group();
			if (timeStr != null) {
				String replace = timeStr.replace("Duration:", "");
				String[] split = replace.split(":");
				int hourTemp = Integer.parseInt(split[0].trim());
				int minuteTemp = Integer.parseInt(split[1].trim());
				Double secondTemp = Double.parseDouble(split[2].trim());
				duration = hourTemp * 60 * 60 + minuteTemp * 60 + secondTemp.intValue();
			}
		}
	}

	private long currentTime(String msg) {
		Pattern pattern = Pattern.compile("time=[^\\s]*\\s{1}");
		Matcher matcher = pattern.matcher(msg);
		long second = 1;
		long minute = second * 60;
		long hour = minute * 60;
		while (matcher.find()) {
			String timeStr = matcher.group();
			if (timeStr != null) {
				String replace = timeStr.replace("time=", "");
				String[] split = replace.split(":");
				int hourTemp = Integer.parseInt(split[0].trim());
				int minuteTemp = Integer.parseInt(split[1].trim());
				Double secondTemp = Double.parseDouble(split[2].trim());
				return hourTemp * 60 * 60 + minuteTemp * 60 + secondTemp.intValue();
			}
		}
		return 0;
	}

	@Override
	public boolean isbroken() {
		return isBroken;
	}

}
